import fs from "fs-extra";
import Excel from "exceljs";

const srcPath = '../../excel/'
const dstClientPath = '../../apps/client/assets/Json/'
const dstServerPath = '../../apps/server/Json/'

const excel2json = async (fileName: string) => {
    const src = srcPath + fileName + '.xlsx'
    const clientDst = dstClientPath + fileName + '.json'
    const serverDst = dstServerPath + fileName + '.json'
    const result: any = {};
    const targets: any = {}//客户端，服务器 谁会用到
    const types: any = {}//数据类型
    const keys: any = {}//字段key

    const workbook = new Excel.Workbook();
    // 读取excel
    await workbook.xlsx.readFile(src);
    const worksheet = workbook.getWorksheet(1); //获取第一个worksheet
    worksheet?.eachRow((row, rowNumber) => {

        if (rowNumber === 3) {
            row.eachCell((cell, colNumber) => {
                targets[colNumber] = cell.value
            });
        } else if (rowNumber === 4) {
            row.eachCell((cell, colNumber) => {
                types[colNumber] = cell.value
            });
        } else if (rowNumber === 5) {
            row.eachCell((cell, colNumber) => {
                keys[colNumber] = cell.value
            });
        } else if (rowNumber > 5) {

            let obj: Record<any, any> = {};
            row.eachCell((cell, colNumber) => {
                if (targets[colNumber] === 'c') {
                    const value = '' + cell.value
                    if (keys[colNumber] === 'sn') {
                        result[value] = obj
                        obj[keys[colNumber]] = value
                    } else if (types[colNumber] === 'array') {
                        obj[keys[colNumber]] = value.split(",").map(v => Number(v))
                    } else if (types[colNumber] === 'int') {
                        obj[keys[colNumber]] = Number(value)
                    } else {
                        obj[keys[colNumber]] = value
                    }
                }
            });
        }
    })
    // 写入流
    fs.writeFile(clientDst, JSON.stringify(result));
    fs.writeFile(serverDst, JSON.stringify(result));
    console.log('=== excel转json 完成', fileName)
}

/** 是不是xlsx文件 */
const isXlsx = (fileName: string) => {
    const arr = fileName.split('.')
    const suffix = arr[arr.length - 1]
    return (fileName[0] != '.' && fileName[0] != '~' && suffix == 'xlsx')
}

/** 是不是json文件 */
const isJson = (fileName: string) => {
    const arr = fileName.split('.')
    const suffix = arr[arr.length - 1]
    return (suffix == 'json')
}

const isExist = () => {
    return new Promise((resolve) => {
        // 判断文件是否存在
        fs.access(dstServerPath, fs.constants.F_OK, (err) => {
            if (err) {
                fs.mkdir("Json", err => {
                    if (err) {
                        console.error('=== ' + err);
                    }
                    resolve(true)
                })
            } else {
                resolve(true)
            }
        });
    })
}

const run = async () => {
    await isExist()
    console.log('========================================')
    fs.readdirSync(dstClientPath).map((fileName: string) => {
        if (isJson(fileName)) {
            fs.unlink(dstClientPath + fileName)
            console.log('=== 删除client文件 ' + fileName)
        }
    })
    console.log('========================================')
    fs.readdirSync(dstServerPath).map((fileName: string) => {
        if (isJson(fileName)) {
            fs.unlink(dstServerPath + fileName)
            console.log('=== 删除server文件 ' + fileName)
        }
    })
    console.log('========================================')

    const prmiseArr: any = []
    fs.readdirSync(srcPath).map((fileName: string) => {
        const arr = fileName.split('.')
        if (isXlsx(fileName)) {
            prmiseArr.push(excel2json(arr[0]))
            console.log('=== 读取文件 ' + fileName)
        }
    })
    Promise.all(prmiseArr).then(() => {
        console.log('========================================')
        console.log('=== excel转json成功')
        console.log('=== excel转json成功')
        console.log('=== excel转json成功')
    }).catch((e) => {
        console.log('========================================')
        console.error(e)
        console.error('=== excel转json失败')
        console.error('=== excel转json失败')
        console.error('=== excel转json失败')
    })
    console.log('========================================')
}

run()